const { Service } = require('egg');
const myDate = require('../utils/myDate');
const md5 = require('../utils/md5');

class UserService extends Service {
  async adduser(userInfo) {
    userInfo.create_time = myDate.getNowDate();
    userInfo.update_time = myDate.getNowDate();
    if (!userInfo.name) {
      userInfo.name = `用户${userInfo.phone}`;
    }
    const result = await this.app.mysql.insert('user', {
      phone: userInfo.phone,
      password: userInfo.password,
      auth: userInfo.auth,
      name: userInfo.name,
      email: userInfo.email,
      sex: userInfo.sex,
      birth_day: myDate.strToDate(userInfo.birth_day),
      home: JSON.stringify(userInfo.home),
    });
    if (result) {
      return true;
    }
    return false;
  }

  async delUser(ids) {
    const res = await this.app.mysql.query(
      `delete from user where id in (${ids.join(',')})`
    );
    if (res) {
      return true;
    }
    return false;
  }

  async updateUser(userInfo) {
    userInfo.birth_day = myDate.strToDate(userInfo.birth_day);
    userInfo.update_time = myDate.getNowDate();
    const isExit = await this.app.mysql.query(
      'SELECT * FROM user WHERE id != ? AND (phone = ? OR email = ?)',
      [ userInfo.id, userInfo.phone, userInfo.email ]
    );
    if (isExit && isExit.length > 0) {
      return {
        state: false,
        msg: '该手机号或邮箱已存在',
      };
    }
    userInfo.home = JSON.stringify(userInfo.home);
    let res = null;
    if (userInfo.password) {
      userInfo.password = md5.getMd5Data(userInfo.password);
      res = await this.app.mysql.update('user', {
        id: userInfo.id,
        auth: userInfo.auth,
        name: userInfo.name,
        email: userInfo.email,
        sex: userInfo.sex,
        birth_day: userInfo.birth_day,
        home: userInfo.home,
        password: userInfo.password,
        update_time: userInfo.update_time,
      });
    } else {
      res = await this.app.mysql.update('user', {
        id: userInfo.id,
        auth: userInfo.auth,
        name: userInfo.name,
        email: userInfo.email,
        sex: userInfo.sex,
        birth_day: userInfo.birth_day,
        home: userInfo.home,
        update_time: userInfo.update_time,
      });
    }
    if (res) {
      return {
        state: true,
        msg: '更新成功',
      };
    }
    return {
      state: false,
      msg: '更新失败',
    };
  }

  async isPhoneOrEmailExit(userInfo) {
    const res = await this.app.mysql.get('user', { phone: userInfo.phone });
    if (res) {
      return res;
    }
    const res2 = await this.app.mysql.get('user', { email: userInfo.email });
    if (res2) {
      return res2;
    }
    return false;
  }

  async getUserInfo(id) {
    const res = await this.app.mysql.get('user', { id });
    if (res) {
      res.password = null;
      return res;
    }
    return false;
  }

  async getUsersInfo(pageNum, pageSize, name, email, phone, auth) {
    if (!pageNum) {
      pageNum = 1;
    }
    if (!pageSize) {
      pageSize = 10;
    }
    let where = '';
    const conditions = [];
    if (name) {
      conditions.push(`name LIKE '%${name}%'`);
    }
    if (phone) {
      conditions.push(`phone LIKE '%${phone}%'`);
    }
    if (email) {
      conditions.push(`email LIKE '%${email}%'`);
    }
    if (auth) {
      conditions.push(`auth = '${auth}'`);
    }
    if (conditions.length > 0) {
      where = `WHERE ${conditions.join(' AND ')}`;
    }
    const totalRes = await this.app.mysql.query(`SELECT COUNT(*) AS total FROM user ${where}`);
    const total = totalRes[0].total;
    const res = await this.app.mysql.query(`SELECT * FROM user ${where} LIMIT ?, ?`, [ (pageNum - 1) * pageSize, pageSize ]);
    if (res) {
      for (let i = 0; i < res.length; i++) {
        res[i].password = null;
        res[i].home = res[i].home ? JSON.parse(res[i].home) : null;
      }
      return {
        users: res,
        total,
      };
    }
    return false;
  }


  async isExit(userInfo) {
    const user = await this.app.mysql.get('user', { phone: userInfo.phone });
    if (!user) {
      return false;
    }
    return user;
  }

  async addAdmin(userInfo) {
    const result = await this.app.mysql.insert('user', {
      phone: userInfo.phone,
      password: md5.getMd5Data(userInfo.password),
      name: `用户${userInfo.phone}`,
      auth: 'admin',
    });
    if (result) {
      return true;
    }
    return false;
  }

}

module.exports = UserService;

